// map.js
import qqMap from '../../../utils/qqmap'
Page({
  data: {
    // 121.618713,31.040674
    latitude: 31.040674,
    longitude: 121.618713,
    markers: [
      {
        id: 1,
        latitude: 31.040674,
        longitude: 121.618713,
        width: 24,
        height: 30,
      },
      {
        id: 2,
        latitude: 31.245414,
        longitude: 121.506379,
        iconPath: '/static/images/marker.png',
        width: 40,
        height: 40,
      },
    ],
    dialogVisible: false,
  },
  onLoad({ id }) {
    this.getRepairDetail(id)
  },
  async getRepairDetail(id) {
    // id 不存在就不必发请求了
    if (!id) return
    // 请求数据接口
    const { code, data: repairDetail } = await wx.http.get('/repair/' + id)
    // 校验接口调用结果
    if (code !== 10000) return wx.utils.toast('获取报修详情失败!')
    // 渲染报修详情
    this.setData({ ...repairDetail })

    // 只有在上门中时才规划路线
    if (this.data.status === 2) {
      this.getPolyLine()
    }
  },
  getPolyLine() {
    qqMap.direction({
      mode: 'bicycling',
      from: '31.040674,121.618713',
      to: '31.245414,121.506379',
      success: (res) => {
        var ret = res
        var coors = ret.result.routes[0].polyline,
          pl = []
        //坐标解压（返回的点串坐标，通过前向差分进行压缩）
        var kr = 1000000
        for (var i = 2; i < coors.length; i++) {
          coors[i] = Number(coors[i - 2]) + Number(coors[i]) / kr
        }
        //将解压后的坐标放入点串数组pl中
        for (var i = 0; i < coors.length; i += 2) {
          pl.push({ latitude: coors[i], longitude: coors[i + 1] })
        }
        console.log(pl)
        //设置polyline属性，将路线显示出来,将解压坐标第一个数据作为起点
        this.setData({
          polyline: [
            {
              points: pl,
              color: '#FF0000DD',
              width: 4,
            },
          ],
        })
      },
      fail: function (error) {
        console.error(error)
      },
      complete: function (res) {
        console.log(res)
      },
    })
  },
  openDialogPlayer() {
    this.setData({
      dialogVisible: true,
    })
  },
  dialogClose(ev) {
    console.log(ev)
    ev.detail === 'confirm' && this.cancelRepair()
  },
  async cancelRepair() {
    const { code } = await wx.http.put(`/cancel/repaire/${this.data.id}`)
    if (code !== 10000) return wx.utils.toast('取消报修失败')
    wx.navigateBack()
  },
  goForm() {
    wx.navigateTo({
      url: `/repair_pkg/pages/form/index?id=${this.data.id}`,
    })
  },
})
